package com.daichi.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daichi.common.dto.LoginDto;
import com.daichi.common.lang.Common;
import com.daichi.common.lang.Result;
import com.daichi.common.vo.UserVo;
import com.daichi.entity.User;
import com.daichi.service.UserService;
import com.daichi.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {

    private final UserService userService;

    private final JwtUtils jwtUtils;

    @Autowired
    public AccountController(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }


    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");

        if (!SecureUtil.md5(loginDto.getPassword()).equals(user.getPassword())) {
            return Result.fail("密码不正确");
        }

        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader(Common.JWT_HEADER,jwt);
        response.setHeader("Access-control-Expose-Headers",Common.JWT_HEADER);

        UserVo userVo = new UserVo();

        BeanUtils.copyProperties(user,userVo);

        return Result.succ(userVo);
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }


}
